//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package issue_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_sprit_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type BurnDownInfoDbItem struct {
	BurnDownInfoId string `bson:"_id"`
	SpritId        string `bson:"spritId"`
	Day            uint32 `bson:"day"`
	MemberUserId   string `bson:"memberUserId"`
	RemainMinutes  uint32 `bson:"remainMinutes"`
}

func (item *BurnDownInfoDbItem) ToBurnDownInfo() *project_sprit_api.BurnDownInfo {
	return &project_sprit_api.BurnDownInfo{
		SpritId:       item.SpritId,
		Day:           item.Day,
		MemberUserId:  item.MemberUserId,
		RemainMinutes: item.RemainMinutes,
	}
}

type _BurnDownInfoDao struct {
	mc *mongo.Collection
}

func newBurnDownInfoDao(db *mongo.Database) (*_BurnDownInfoDao, error) {
	mc := db.Collection(db_ns.DB_NS_ISSUE + "burn_down")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"spritId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_BurnDownInfoDao{mc: mc}, nil
}

func (db *_BurnDownInfoDao) Set(ctx context.Context, dbItem *BurnDownInfoDbItem) error {
	dbItem.BurnDownInfoId = db.genBurnDownInfoId(dbItem.SpritId, dbItem.Day, dbItem.MemberUserId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.BurnDownInfoId, "spritId": dbItem.SpritId},
		bson.M{"$set": dbItem},
		options.Update().SetUpsert(true))
	return err
}

func (db *_BurnDownInfoDao) genBurnDownInfoId(spritId string, day uint32, memberUserId string) string {
	return fmt.Sprintf("%s%d%s", spritId, day, memberUserId)
}

func (db *_BurnDownInfoDao) ListBySprit(ctx context.Context, spritId string) ([]*BurnDownInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"spritId": spritId})
	if err != nil {
		return nil, err
	}
	retList := []*BurnDownInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
